<template>
  <view class="uni-container">
    <uni-forms ref="form" :model="formData" validateTrigger="bind">
      <uni-forms-item name="title" label="采购单名称">
        <uni-easyinput placeholder="请输入采购单名称" v-model="formData.title"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="serial_number" label="采购单编号">
        <uni-easyinput placeholder="例如：CG-20250819-001" v-model="formData.serial_number"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="description" label="详细描述">
        <uni-easyinput type="textarea" placeholder="请输入规格、型号等详细信息" v-model="formData.description"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="start_price" label="起始价格">
        <uni-easyinput type="digit" placeholder="请输入起始价格" v-model="formData.start_price"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="end_time" label="报价截止时间">
        <uni-datetime-picker return-type="timestamp" v-model="formData.end_time"></uni-datetime-picker>
      </uni-forms-item>
      <uni-forms-item name="attachments" label="采购附件">
        <uni-file-picker v-model="formData.attachments" file-mediatype="all" :limit="5"></uni-file-picker>
      </uni-forms-item>
      <uni-forms-item name="status" label="状态">
        <uni-data-checkbox v-model="formData.status" :localdata="formOptions.status_localdata"></uni-data-checkbox>
      </uni-forms-item>
      <uni-forms-item name="invited_supplier_ids" label="受邀供应商">
        <uni-data-checkbox :multiple="true" v-model="formData.invited_supplier_ids"></uni-data-checkbox>
      </uni-forms-item>
      <uni-forms-item name="winner_supplier_id" label="中标供应商">
        <uni-easyinput placeholder="中标的供应商ID" v-model="formData.winner_supplier_id"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="create_time" label="创建时间">
        <uni-datetime-picker return-type="timestamp" v-model="formData.create_time"></uni-datetime-picker>
      </uni-forms-item>
      <uni-forms-item name="finish_time" label="结束时间">
        <uni-datetime-picker return-type="timestamp" v-model="formData.finish_time"></uni-datetime-picker>
      </uni-forms-item>
      <view class="uni-button-group">
        <button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
        <button class="uni-button" style="width: 100px; margin-left: 15px;" @click="navigateBack">返回</button>
      </view>
    </uni-forms>
  </view>
</template>

<script>
  import { validator } from '../../js_sdk/validator/auctions.js';

  const db = uniCloud.database();
  const dbCmd = db.command;
  const dbCollectionName = 'auctions';

  function getValidator(fields) {
    let result = {}
    for (let key in validator) {
      if (fields.includes(key)) {
        result[key] = validator[key]
      }
    }
    return result
  }

  

  export default {
    data() {
      let formData = {
        "title": null,
        "serial_number": null,
        "description": null,
        "start_price": null,
        "end_time": null,
        "attachments": [],
        "status": "",
        "invited_supplier_ids": [],
        "winner_supplier_id": "",
        "create_time": null,
        "finish_time": null
      }
      return {
        formData,
        formOptions: {
          "status_localdata": [
            {
              "value": "bidding",
              "text": "bidding"
            },
            {
              "value": "finished",
              "text": "finished"
            }
          ]
        },
        rules: {
          ...getValidator(Object.keys(formData))
        }
      }
    },
    onLoad(e) {
      if (e.id) {
        const id = e.id
        this.formDataId = id
        this.getDetail(id)
      }
    },
    onReady() {
      this.$refs.form.setRules(this.rules)
    },
    methods: {
      /**
       * 返回上一页
       */
      navigateBack() {
        uni.navigateBack()
      },
      
      /**
       * 验证表单并提交
       */
      submit() {
        uni.showLoading({
          mask: true
        })
        this.$refs.form.validate().then((res) => {
          return this.submitForm(res)
        }).catch(() => {
        }).finally(() => {
          uni.hideLoading()
        })
      },

      /**
       * 提交表单
       */
      submitForm(value) {
        // 使用 clientDB 提交数据
        return db.collection(dbCollectionName).doc(this.formDataId).update(value).then((res) => {
          uni.showToast({
            title: '修改成功'
          })
          this.getOpenerEventChannel().emit('refreshData')
          setTimeout(() => uni.navigateBack(), 500)
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        })
      },

      /**
       * 获取表单数据
       * @param {Object} id
       */
      getDetail(id) {
        uni.showLoading({
          mask: true
        })
        db.collection(dbCollectionName).doc(id).field("title,serial_number,description,start_price,end_time,attachments,status,invited_supplier_ids,winner_supplier_id,create_time,finish_time").get().then((res) => {
          const data = res.result.data[0]
          if (data) {
            this.formData = data
            
          }
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        }).finally(() => {
          uni.hideLoading()
        })
      }
    }
  }
</script>
